<template>
	<view class="setDevice">
		<custom-bar :custonName="identity ? details.devName : details.devCustomName">
		</custom-bar>
		<view class="set-top">
			<view class="" style="display: contents; align-items: flex-start" v-if="roomTemp && roomTemp != '故障'">
				<text>{{ roomTemp }}</text>
				<image src="@/static/icons/tem.svg" mode="aspectFit" class="c"></image>
			</view>
			<view class="" v-if="roomTemp == '故障'">
				<image src="@/static/icons/redtanhao.svg" mode="aspectFit" style="width: 200rpx; height: 200rpx">
				</image>
			</view>
			<view class="set-top-position" v-if="roomTemp && roomTemp != '故障'">
				<image src="@/static/icons/devhum20ade5.svg" mode="" class="devhumIcon"></image>
				<text style="padding-left: 5rpx">{{ details.devhum }}%</text>
			</view>
		</view>
		<view class="set-center">
			<view class="set-center-error">
				<text v-if="tempTopBtn">最高温度不超过{{ details.tempSetTop }}℃</text>
				<text v-if="tempLowBtn">最低温度不低于{{ details.tempSetBot }}℃</text>
			</view>
			<view class="set-center-action">
				<view class="set-center-action-center">
					<view class=""> 设定温度:{{ details.devTempset }}℃</view>
					<view class="set-center-action-show">
						<view class="">
							<image src="@/static/icons/lock21aee5.svg" mode="aspectFit"
								class="set-center-action-aside-icon" v-if="switchValue == true">
							</image>
							<image src="@/static/icons/lock8a8a8a.svg" mode="aspectFit"
								class="set-center-action-aside-icon" v-else>
							</image>
						</view>
						<view class="">
							<image src="@/static/icons/heat.png" alt="" mode="aspectFit"
								class="set-center-action-aside-icon"
								v-if="details.devErrBit2 == '1' && locacalFlag == '1'"></image>
							<image src="@/static/icons/firered.png" alt="" mode="aspectFit"
								class="set-center-action-aside-icon"
								v-if="details.devErrBit4 == '1' && locacalFlag == '1'"></image>
							<image src="@/static/icons/fired4237a.svg" mode="aspectFit"
								class="set-center-action-aside-icon"
								v-if="details.devHeating == '1' && locacalFlag == '1'">
							</image>
						</view>
					</view>

					<view class="set-center-action-control">
						<view class="" style="width: 33%">
							<image src="@/static/icons/add21aee5.svg" mode="aspectFit"
								class="set-center-action-control-add" @click="changeStatus('top')" v-if="
                  !tempTopBtn &&
                  locacalFlag == '1' &&
                  localMode != '2'
                ">
							</image>
							<image src="@/static/icons/add8a8a8a.svg" mode="aspectFit"
								class="set-center-action-control-add" v-if="
                  tempTopBtn &&
                  locacalFlag == '1' &&
                  localMode != '2'
                ">
							</image>
						</view>

						<view class="" @click="changeStatus('status')" style="width: 34%">
							<!-- 开机 -->
							<image src="@/static/icons/action.svg" mode="aspectFit"
								class="set-center-action-control-switch" v-if="locacalFlag == '1'"></image>
							<!-- 关机 -->
							<image src="@/static/icons/action8a8a8a.svg" mode="aspectFit"
								class="set-center-action-control-switch" v-else></image>
						</view>
						<view class="" style="width: 33%">
							<image src="@/static/icons/sub21aee5.svg" mode="aspectFit"
								class="set-center-action-control-sub" v-if="
                  !tempLowBtn &&
                  locacalFlag== '1' &&
                  localMode != '2'
                " @click="changeStatus('low')">
							</image>
							<image src="@/static/icons/sub8a8a8a.svg" mode="aspectFit"
								class="set-center-action-control-sub" style="width:85rpx;height:85rpx；margin-top:-5rpx"
								v-if="
                  tempLowBtn &&
                  locacalFlag == '1' &&
                  localMode != '2'
                ">
							</image>
						</view>
					</view>
				</view>
			</view>
			<view class="set-center-electric">
				<view class="set-center-electric-item">
					<image src="@/static/icons/w21aee5.svg" mode="" style="
              width: 65rpx;
              height: 65rpx;
              vertical-align: middle;
              padding-right: 3rpx;
              padding-left: 5rpx;
            "></image>
					<text>{{ details.devPower }}W</text><up-icon name="error" color="red"
						v-if="details.devErrBit6 == '1'"></up-icon>
				</view>
				<view class="set-center-electric-item">
					<image src="@/static/icons/V21aee5.svg" mode="" style="
              width: 47rpx;
              height: 47rpx;
              vertical-align: middle;
              padding-right: 5rpx;
              padding-left: 5rpx;
            "></image>
					<text>{{ details.devVoltage }}V</text><up-icon name="error" color="red"
						v-if="details.devErrBit5 == '1'"></up-icon>
				</view>
				<view class="set-center-electric-item">
					<image src="@/static/icons/A20ade5.svg" mode="" style="
              width: 57rpx;
              height: 57rpx;
              vertical-align: middle;
              padding-right: 3rpx;
              padding-left: 5rpx;
            "></image>
					<text v-if="details.devCurr == '0.00'">0A</text>
					<text v-else>{{ details.devCurr }}</text>
				</view>
			</view>
			<view class="set-center-mode">
				<view :class="
            localMode == '1'
              ? 'set-center-mode-choose'
              : 'set-center-mode-choose-not'
          " @click="changeMode('1')">
					<view class="set-center-mode-choose-image">
						<image src="@/static/icons/otempffffff.svg" mode="" style="width: 55rpx; height: 55rpx"
							v-if="localMode == '1'"></image>
						<image src="@/static/icons/otemp8a8a8a.svg" mode="" style="width: 55rpx; height: 55rpx" v-else>
						</image>
					</view>
					<view>恒温模式</view>
				</view>
				<view :class="
            localMode == '2'
              ? 'set-center-mode-choose'
              : 'set-center-mode-choose-not'
          " class="set-center-mode-choose" @click="changeMode('2')">
					<view class="set-center-mode-choose-image">
						<image src="@/static/icons/headffffff.svg" mode="" style="width: 70rpx; height: 66rpx"
							v-if="localMode == '2'"></image>
						<image src="@/static/icons/head8a8a8a.svg" mode="" style="width: 70rpx; height: 66rpx" v-else>
						</image>
					</view>
					<view>智能模式</view>
				</view>
			</view>
		</view>

		<view class="set-bottom">
			<view class="set-bottom-more" @click="goExtends">
				更多
				<uni-icons type="right" size="20" color="#8a8a8a"></uni-icons>
			</view>

			<view class="set-bottom-list" @click="handleKeyChange">
				<view class="set-bottom-list-left">
					<image src="@/static/icons/lock.svg" mode="" class="set-bottom-list-left-icon"></image>
					<view class="set-bottom-list-left-icon-title"> 童锁功能 </view>
				</view>
				<view class="set-bottom-list-right">
					<view class="">
						<!-- <text>{{getLabel('sys_devchild_lock',details.devchildLock)}}</text> -->
					</view>
					<view class="set-bottom-list-right-icon">
						<up-switch v-model="switchValue" @change="changeSwitch" activeColor="#20aee5"
							:disabled="switchDisable"></up-switch>
					</view>
				</view>
			</view>

			<view class="set-bottom-list">
				<view class="set-bottom-list-left">
					<image src="@/static/icons/clock.svg" mode="" class="set-bottom-list-left-icon"></image>
					<view class="set-bottom-list-left-icon-title"> 智能配置</view>
				</view>
				<view class="set-bottom-list-right" @click="goSetTime">
					<view class="set-bottom-list-right-icon" style="width: 80rpx; text-align: right">
						<uni-icons type="right" size="20" color="#8a8a8a"></uni-icons>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted,
		watch
	} from "vue";
	import {
		onLoad,
		onUnload,
		onShow, // 添加这个导入
		onHide, // 添加这个导入
	} from "@dcloudio/uni-app";
	const deviceInfo = ref({});
	const switchValue = ref(false); // 解锁
	const changePopup = ref(null);
	const popupTitle = ref("");
	const setTimeDrawer = ref(null);
	const deviceId = ref("");
	const deviceName = ref("");
	const dataId = ref("");
	const details = ref({});
	const tempTopBtn = ref(false);
	const tempLowBtn = ref(false);
	const infoTimer = ref(null);
	const timerInterval = ref(5000); // 5秒间隔，可根据需要调整
	const devModeIndex = ref(null);
	const modeList = ref([]);
	const tempInfo = ref(null);
	const identity = ref(null);
	const switchDisable = ref(false);
	const roomTemp = ref("");
	const debounceTimer = ref(null); // 防抖
	const switchDebounceTimer = ref(null); // 童锁防抖
	const lastUserActionTime = ref(0); // 最后用户操作时间
	const locacalFlag = ref(null)
	const localMode = ref(null)
	onLoad((options) => {
		let code = decodeURIComponent(options.id);
		if (code) {
			deviceId.value = Number(code);
			deviceName.value = decodeURIComponent(options.devName);
		}
	});
	// 页面显示时可以刷新数据（可选）
	onShow(() => {
		// 如果需要在返回时刷新数据，可以调用以下方法
		startInfoTimer();
		getDevInfo(deviceId.value);
		identity.value = uni.getStorageSync("identity");
	});

	// 页面隐藏时的操作（可选）
	onHide(() => {
		// 可以在这里处理页面隐藏时的逻辑
		stopInfoTimer();
	});
	// 页面卸载时清除所有定时器
	onUnmounted(() => {
		stopInfoTimer();
		if (switchDebounceTimer.value) {
			clearTimeout(switchDebounceTimer.value);
		}
		if (debounceTimer.value) {
			clearTimeout(debounceTimer.value);
		}
	});

	// uni-app页面卸载时也清除定时器
	onUnload(() => {
		stopInfoTimer();
		// 清理防抖定时器
		if (switchDebounceTimer.value) {
			clearTimeout(switchDebounceTimer.value);
		}
		if (debounceTimer.value) {
			clearTimeout(debounceTimer.value);
		}
	});
	watch(tempLowBtn, (newVal) => {
		if (newVal) {
			setTimeout(() => {
				tempLowBtn.value = false;
			}, 3000);
		}
	});
	// 监听tempTopBtn变化
	watch(tempTopBtn, (newVal) => {
		if (newVal) {
			setTimeout(() => {
				tempTopBtn.value = false;
			}, 3000);
		}
	});
	const changeSwitch = (e) => {
		// 记录用户操作时间
		lastUserActionTime.value = Date.now();
		// 立即更新UI给用户反馈
		switchValue.value = e;
		stopInfoTimer();

		// 清除之前的定时器
		if (switchDebounceTimer.value) {
			clearTimeout(switchDebounceTimer.value);
			switchDebounceTimer.value = null;
		}

		// 设置新的防抖定时器
		switchDebounceTimer.value = setTimeout(() => {
			executeSwitchChange(e);
		}, 1000); // 1秒防抖延迟
	};

	// 实际执行函数
	const executeSwitchChange = (e) => {
		let data = {
			equipNo: details.value.equipNo,
			id: details.value.id,
		};

		// 切换童锁状态
		if (e) {
			data.devchildLock = 1;
		} else {
			data.devchildLock = 0;
		}

		uni.$u.http
			.post("/wechat/editSend", data)
			.then((res) => {
				if (res.success) {
					uni.showToast({
						title: "操作成功",
						icon: "success",
					});
				}

			})
			.catch((error) => {
				// 操作失败，回滚UI状态
				switchValue.value = !e;
			})
			.finally(() => {
				// 接口调用完成后重启定时器
				setTimeout(() => {
					startInfoTimer();
				}, 2000);
			});
	};
	const changeStatus = (val) => {
		if (identity.value == false) {
			// 0  解锁  1 锁后台  2 开放开关机 3 全锁
			if (details.value.devKeyLock == 3) {
				uni.showToast({
					title: "设备已锁定,无法操作",
					icon: "none",
				});
				return;
			}
		}
		if (typeof wx !== "undefined" && wx.vibrateShort) {
			// 调用微信短震动API，持续约15ms
			wx.vibrateShort({});
		}
		lastUserActionTime.value = Date.now();
		if (val == "status") {
			// 开机关机设置
			let status = locacalFlag.value == "1" ? "0" : "1";
			let data = {
				equipNo: details.value.equipNo,
				devOnOff: Number(status),
				id: details.value.id,
			};
			locacalFlag.value = status;
			uni.$u.http.post("/wechat/editSend", data).then((res) => {
				// 如果接口调用失败，回滚本地状态

				if (res.success) {
					uni.showToast({
						title: "操作成功",
						icon: "success",
					});
				}
			}).finally(() => {
				startInfoTimer();
			});;
		}

		if (val == "top" || val == "low") {
			if (identity.value == false) {
				// 0  解锁  1 锁后台  2 开放开关机 3 全锁
				if (details.value.devKeyLock == 2) {
					uni.showToast({
						title: "设备已锁定,无法操作",
						icon: "none",
					});
					return;
				}
			}
			let topTemp = Number(details.value.tempSetTop) || 50; // 温控上线
			let heatBot = Number(details.value.tempSetBot) || 5; // 温控下载
			let Tempset; // 目标温度
			// Tempset = details.value.devRunMode == '2'?details.value.devSTemp:details.value.devTempsetM;
			Tempset = details.value.devTempset;
			// 智能模式 2 恒温模式 1
			let temp = Number(Tempset);
			if (val == "top") {
				if (heatBot < topTemp && temp < topTemp) {
					temp += 1;
					details.value.devTempset = temp.toString();
					tempLowBtn.value = false;
				} else {
					tempTopBtn.value = true;
					return;
				}
			}
			if (val == "low") {
				if (heatBot < topTemp && heatBot < temp) {
					temp -= 1;
					details.value.devTempset = temp.toString();
					tempTopBtn.value = false;
				} else {
					tempLowBtn.value = true;
					return;
				}
			}

			let data = {
				equipNo: details.value.equipNo,
				devTempset: temp,
				id: details.value.id,
			};

			// 使用防抖调用，1秒内只执行最后一次
			debounceApiCall(data);
		}
	};
	// 添加防抖函数
	const debounceApiCall = (data) => {
		// 清除之前的定时器
		if (debounceTimer.value) {
			clearTimeout(debounceTimer.value);
		}
		// 立即停止设备信息定时器
		stopInfoTimer();
		// 设置新的定时器
		debounceTimer.value = setTimeout(() => {
			uni.$u.http
				.post("/wechat/editSend", data)
				.then((res) => {
					// 可以在这里处理响应结果
				}).finally(() => {
					// 在接口调用完成后延迟2秒再重启定时器
					setTimeout(() => {
						startInfoTimer();
					}, 2000); // 2秒后重启定时器
				});
		}, 1000); // 1秒内只执行最后一次调用
	};

	const handleKeyChange = () => {
		if (identity.value == false) {
			// 0  解锁  1 锁后台  2 开放开关机 3 全锁
			if (details.value.devKeyLock == 3 || details.value.devKeyLock == 2) {
				uni.showToast({
					title: "设备已锁定,无法操作",
					icon: "none",
				});
				return;
			}
		}
	};
	const goExtends = () => {
		uni.navigateTo({
			url: `/Device/extendsSet/extendsSet?equipNo=${encodeURIComponent(
      deviceId.value
    )}&&devName=${deviceName.value}`,
		});
	};

	const goSetTime = () => {
		uni.navigateTo({
			url: `/Device/setInterlval/setInterlval?equipNo=${encodeURIComponent(
      details.value.equipNo
    )}&&id=${details.value.id}&&devName=${deviceName.value}`,
		});
	};

	const getLabel = (type, value) => {
		let arr = uni.getStorageSync(type) || [];
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].dictValue == value) {
				return arr[i].dictLabel;
			}
		}
		return "-";
	};
	const getDevInfo = (devId) => {
		let data = {
			id: devId || deviceId.value,
		};
		uni.$u.http.post("/wechat/getDevInfo", data).then((res) => {
			if (res.success) {
				details.value = res.data;
				dataId.value = res.data.id;
				// 童锁处理 - 基于时间判断是否应该更新
				const serverUpdateTime = Date.now();

				// 如果服务器更新时间晚于最后一次用户操作时间，则更新UI
				if (serverUpdateTime > lastUserActionTime.value + 1500) {
					if (res.data.devchildLock == "1") {
						// 1 上锁
						switchValue.value = true;
					} else {
						// 0 解锁
						switchValue.value = false;
					}
					locacalFlag.value = details.value.devOnOff
					localMode.value = details.value.devRunMode
					// 1.5秒缓冲时间
				}

				if (identity.value == false) {
					if (details.value.devKeyLock == 3 || details.value.devKeyLock == 2) {
						switchDisable.value = true;
					} else {
						switchDisable.value = false;
					}
				}
				// 判断室温是否故障
				if (
					details.value.devTemp1.includes("32768") ||
					details.value.devTemp1.includes("32767")
				) {
					roomTemp.value = "故障";
				} else {
					roomTemp.value = details.value.devTemp1;
				}
			}
		});
	};

	const changeMode = (val) => {
		lastUserActionTime.value = Date.now();
		if (identity.value == false) {
			// 0  解锁  1 锁后台  2 开放开关机 3 全锁
			if (details.value.devKeyLock == 3 || details.value.devKeyLock == 2) {
				uni.showToast({
					title: "设备已锁定,无法操作",
					icon: "none",
				});
				return;
			}
		}
		localMode.value = val;
		stopInfoTimer();
		let data = {
			id: details.value.id,
			devRunMode: Number(val),
			equipNo: details.value.equipNo,
		};
		uni.$u.http.post("/wechat/editSend", data).then((res) => {
			if (res.success) {
				uni.showToast({
					title: "操作成功",
					icon: "success",
				});
				details.value.devchildLock = data.devchildLock
			}
		}).finally(() => {
			startInfoTimer();
		});
	};

	// 添加启动定时器的方法
	const startInfoTimer = () => {
		// 清除现有的定时器
		if (infoTimer.value) {
			clearInterval(infoTimer.value);
		}

		// 设置新的定时器
		infoTimer.value = setInterval(() => {
			getDevInfo(deviceId.value);
		}, timerInterval.value);
	};

	// 添加停止定时器的方法
	const stopInfoTimer = () => {
		if (infoTimer.value) {
			clearInterval(infoTimer.value);
			infoTimer.value = null;
		}
	};
</script>

<style lang="scss" scoped>
	@import "./setDevice.scss";
</style>